/**
 * 工具函数组合式
 */

/**
 * 防抖组合式函数
 * @param fn 要执行的函数
 * @param delay 延迟时间（毫秒）
 */
export function useDebounce<T extends (...args: any[]) => any>(
  fn: T,
  delay: number = 300
) {
  let timeout: ReturnType<typeof setTimeout> | null = null
  
  const debounced = (...args: Parameters<T>) => {
    if (timeout) {
      clearTimeout(timeout)
    }
    
    timeout = setTimeout(() => {
      fn(...args)
    }, delay)
  }
  
  const cancel = () => {
    if (timeout) {
      clearTimeout(timeout)
      timeout = null
    }
  }
  
  return {
    debounced: debounced as T,
    cancel
  }
}

/**
 * 节流组合式函数
 * @param fn 要执行的函数
 * @param delay 延迟时间（毫秒）
 */
export function useThrottle<T extends (...args: any[]) => any>(
  fn: T,
  delay: number = 300
) {
  let timeout: ReturnType<typeof setTimeout> | null = null
  let lastExecTime = 0
  
  const throttled = (...args: Parameters<T>) => {
    const currentTime = Date.now()
    
    if (currentTime - lastExecTime > delay) {
      fn(...args)
      lastExecTime = currentTime
    } else {
      if (timeout) {
        clearTimeout(timeout)
      }
      
      timeout = setTimeout(() => {
        fn(...args)
        lastExecTime = Date.now()
      }, delay - (currentTime - lastExecTime))
    }
  }
  
  const cancel = () => {
    if (timeout) {
      clearTimeout(timeout)
      timeout = null
    }
  }
  
  return {
    throttled: throttled as T,
    cancel
  }
}

/**
 * 格式化工具函数
 */
export const formatters = {
  /**
   * 格式化金额
   */
  money: (amount: number, currency = '¥'): string => {
    return `${currency}${(amount / 100).toFixed(2)}`
  },
  
  /**
   * 格式化日期
   */
  date: (dateStr: string, format = 'YYYY-MM-DD'): string => {
    if (!dateStr) return ''
    
    const date = new Date(dateStr)
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    const seconds = String(date.getSeconds()).padStart(2, '0')
    
    return format
      .replace('YYYY', String(year))
      .replace('MM', month)
      .replace('DD', day)
      .replace('HH', hours)
      .replace('mm', minutes)
      .replace('ss', seconds)
  },
  
  /**
   * 格式化数字
   */
  number: (num: number, decimals = 0): string => {
    return num.toFixed(decimals)
  },
  
  /**
   * 格式化百分比
   */
  percent: (value: number, decimals = 1): string => {
    return `${(value * 100).toFixed(decimals)}%`
  },
  
  /**
   * 格式化手机号
   */
  phone: (phone: string): string => {
    if (!phone) return ''
    const cleaned = phone.replace(/\D/g, '')
    if (cleaned.length === 11) {
      return cleaned.replace(/(\d{3})(\d{4})(\d{4})/, '$1 $2 $3')
    }
    return phone
  },
  
  /**
   * 格式化文件大小
   */
  fileSize: (bytes: number): string => {
    if (bytes === 0) return '0 B'
    
    const k = 1024
    const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
    const i = Math.floor(Math.log(bytes) / Math.log(k))
    
    return `${parseFloat((bytes / Math.pow(k, i)).toFixed(2))} ${sizes[i]}`
  }
}

/**
 * 验证工具函数
 */
export const validators = {
  /**
   * 验证手机号
   */
  phone: (phone: string): boolean => {
    return /^1[3-9]\d{9}$/.test(phone)
  },
  
  /**
   * 验证邮箱
   */
  email: (email: string): boolean => {
    return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)
  },
  
  /**
   * 验证身份证
   */
  idCard: (id: string): boolean => {
    return /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/.test(id)
  },
  
  /**
   * 验证数字
   */
  number: (value: string): boolean => {
    return /^\d+(\.\d+)?$/.test(value)
  },
  
  /**
   * 验证整数
   */
  integer: (value: string): boolean => {
    return /^\d+$/.test(value)
  },
  
  /**
   * 验证正整数
   */
  positiveInteger: (value: string): boolean => {
    return /^[1-9]\d*$/.test(value)
  }
}